#ifndef CONFIG_H
#define CONFIG_H

#include <Arduino.h>
#include <FS.h>
#include <LittleFS.h>
#include <ArduinoJson.h>

struct Config {
  char mqttServer[40] = "homeassistant.local";
  int mqttPort = 1883;
  char mqttUser[20] = "";
  char mqttPassword[20] = "";
  char mqttTopic[30] = "home/sensor/room1";
};

bool loadConfig(Config &config) {
  if (!LittleFS.begin()) {
    Serial.println("无法挂载LittleFS");
    return false;
  }
  
  if (!LittleFS.exists("/config.json")) {
    Serial.println("配置文件不存在");
    return false;
  }
  
  File configFile = LittleFS.open("/config.json", "r");
  if (!configFile) {
    Serial.println("无法打开配置文件");
    return false;
  }
  
  size_t size = configFile.size();
  std::unique_ptr<char[]> buf(new char[size]);
  configFile.readBytes(buf.get(), size);
  configFile.close();
  
  DynamicJsonDocument doc(1024);
  auto error = deserializeJson(doc, buf.get());
  if (error) {
    Serial.println("解析配置文件失败");
    return false;
  }
  
  strlcpy(config.mqttServer, doc["mqttServer"] | "homeassistant.local", sizeof(config.mqttServer));
  config.mqttPort = doc["mqttPort"] | 1883;
  strlcpy(config.mqttUser, doc["mqttUser"] | "", sizeof(config.mqttUser));
  strlcpy(config.mqttPassword, doc["mqttPassword"] | "", sizeof(config.mqttPassword));
  strlcpy(config.mqttTopic, doc["mqttTopic"] | "home/sensor/room1", sizeof(config.mqttTopic));
  
  return true;
}

bool saveConfig(Config &config) {
  if (!LittleFS.begin()) {
    Serial.println("无法挂载LittleFS");
    return false;
  }
  
  DynamicJsonDocument doc(1024);
  doc["mqttServer"] = config.mqttServer;
  doc["mqttPort"] = config.mqttPort;
  doc["mqttUser"] = config.mqttUser;
  doc["mqttPassword"] = config.mqttPassword;
  doc["mqttTopic"] = config.mqttTopic;
  
  File configFile = LittleFS.open("/config.json", "w");
  if (!configFile) {
    Serial.println("无法创建配置文件");
    return false;
  }
  
  serializeJson(doc, configFile);
  configFile.close();
  
  return true;
}

#endif